package videoCapture;

import javax.swing.JFrame;

import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FFmpegFrameRecorder;
import com.googlecode.javacv.Frame;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.avutil;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

public class Audio {
	public static void main(String[] args) throws java.lang.Exception {
		CanvasFrame canvas = new CanvasFrame("test");
		OpenCVFrameGrabber grabber = OpenCVFrameGrabber.createDefault(0);
//		FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault("test.avi");
//		String[] strs = OpenCVFrameGrabber.getDeviceDescriptions();
//		for(String s : strs)
//			System.out.println(s);
		
		
		
		
		Frame frame;
		IplImage img;
	
		canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		grabber.start();
		img = grabber.grab();
		int width = img.width();
		int height = img.height();
		
		FFmpegFrameRecorder recorder = new FFmpegFrameRecorder("test.mp4",  width,height);
        recorder.setVideoCodec(13);
        recorder.setFormat("mp4");
//        recorder.setPixelFormat(avutil.);
        recorder.setFrameRate(30);
        recorder.setVideoBitrate(10 * 1024 * 1024);

		
		
		System.out.println(width+" "+height);
		canvas.setCanvasSize(width, height);
		canvas.setVisible(true);
		
		int i = 0;
		recorder.start();
		while(true){
			img = grabber.grab();
//			将IplImage变成数组然后再变成IplImage，模拟网络传输
//			BufferedImage bimg = img.getBufferedImage();
//			ByteArrayOutputStream out = new ByteArrayOutputStream();  
//            ImageIO.write(bimg, "jpg", out);  
//            byte[] b = out.toByteArray(); 
//            ByteArrayInputStream bin = new ByteArrayInputStream(b);
//            BufferedImage bimg2 = ImageIO.read(bin);
//            IplImage img2 = IplImage.createFrom(bimg2);
			
			canvas.showImage(img);
//			recorder.record(img);
			if(i++ > 100){
////				ByteBuffer buffer = img.getByteBuffer();
////				IplImage image = cvDecodeImage(cvMat(1, b.length, CV_8UC1, new BytePointer(b)));
//				ImageIO.write(img.getBufferedImage(), "jpg", new File("test.jpg"));
				break;
			}
		}
		recorder.stop();
		
		canvas.dispose();
	}
}
